import MessageManager from "../../Util/MessageManager";
import GateController from "./gate/GateController";

export default class NetWork {
    private webSocket: WebSocket = null;

    public connect(ws: string) {
        this.webSocket = new WebSocket(ws);
        this.webSocket.binaryType = 'arraybuffer';
        this.webSocket.onopen = (event: Event) => {
            console.log("NetWork.connect()===>onopen~");

            // 开启心跳
            GateController.instance.startHeart();
        }

        this.webSocket.onerror = (event: Event) => {
            console.log("NetWork.connect()===>onerror~");
        }

        this.webSocket.onclose = (event: CloseEvent) => {
            console.log("NetWork.connect()===>onclose~");
        }

        this.webSocket.onmessage = (event: MessageEvent) => {
            // console.log("NetWork.connect()===>onmessage:", event.data);

            const arr = event.data.split('#');
            const msgID = Number(arr[0]);
            MessageManager.instance.onMsg(msgID, arr[1]);
        }
    }

    public send(data: string) {
        // console.log("NetWork.send()===>send~");
        if (!this.webSocket) {
            console.error("NetWork.send()===>webSocket null.");
            return;
        }

        if (this.webSocket && this.webSocket.readyState !== 1) {
            console.error("NetWork.send()===>readyState:", this.webSocket.readyState);
            return;
        }
        this.webSocket.send(data);
    }

    public close() {
        this.webSocket && this.webSocket.close();
        this.webSocket = null;
    }
}